package impl

import (
	dao2 "gin-ranking/api/auth/dao"
	"gin-ranking/api/auth/params"
	result2 "gin-ranking/api/auth/result"
	"gin-ranking/common/page"
	"gin-ranking/common/result"
	"gin-ranking/common/util"
	"strings"
)

type UserServiceImpl struct{}

// Register 用户注册
func (UserServiceImpl) Register(param params.UserRegisterParam) string {

	// 判断用户是否存在
	userVo := dao2.UserDao{}.QueryUserByUsername(param.UserName)
	if len(userVo.UserId) > 0 {
		panic(result.FailEnum(result.CodeMsg1001))
	}
	// 注册
	return dao2.UserDao{}.Save(param.UserName, param.Password).UserId
}

// Login 用户登录
func (UserServiceImpl) Login(param params.UserLoginParam) string {
	// 判断用户是否存在
	userVo := dao2.UserDao{}.QueryUserByUsername(param.UserName)
	if len(userVo.UserId) < 1 {
		panic(result.FailEnum(result.CodeMsg1004))
	}

	if !strings.EqualFold(userVo.Password, util.Md5ToString(param.Password)) {
		panic(result.FailEnum(result.CodeMsg1005))
	}

	dao2.UserSessionDao{}.DeleteId(userVo.UserId)
	token := dao2.UserSessionDao{}.Save(userVo.UserId)
	return token
}

// QueryPageList 分页查询
func (UserServiceImpl) QueryPageList(param params.UserQueryPageListParam) page.Result[[]result2.UserResult] {
	data := dao2.UserDao{}.QueryPageList(param)
	return data
}

// QueryById 根据主键查询
func (UserServiceImpl) QueryById(id string) result2.UserResult {
	return dao2.UserDao{}.QueryById(id)
}

// QueryList 获取用户列表
func (UserServiceImpl) QueryList(param params.UserQueryListParam) []result2.UserResult {
	return dao2.UserDao{}.QueryList(param)
}

// DeleteByIds 根据主键删除
func (UserServiceImpl) DeleteByIds(ids []string) {
	dao2.UserDao{}.DeleteByIds(ids)
}

// Add 添加用户
func (UserServiceImpl) Add(param params.UserAddParam) string {
	// 判断用户是否存在
	userVo := dao2.UserDao{}.QueryUserByUsername(param.UserName)
	if len(userVo.UserId) > 0 {
		panic(result.FailEnum(result.CodeMsg1001))
	}
	// 注册
	return dao2.UserDao{}.Save(param.UserName, param.Password).UserId
}

// Edit 用户编辑
func (UserServiceImpl) Edit(param params.UserEditParam) {
	userVo := dao2.UserDao{}.QueryUserByUsername(param.UserName)
	if !strings.EqualFold(userVo.UserId, param.UserId) {
		panic(result.FailEnum(result.CodeMsg1001))
	}
	dao2.UserDao{}.Update(param)
}
